package cn.zxf.note.note.review;

import com.github.zengxf.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.transaction.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.zxf.note.note.review.NoteReviewStatusEnum.INITIAL;
import static cn.zxf.note.note.review.NoteReviewStatusEnum.REVIEWED;

@Component
public class NoteReviewSupport {

    @Autowired
    private NoteReviewRepository repos;

    @Transactional
    public void batchInsert(Integer userId, Integer noteId) {
        List<NoteReview> list = toList(LocalDateTime.now(), userId, noteId);
        repos.saveAll(list);
    }

    @Transactional
    public void batchInsertForImport(LocalDate date, Integer userId, Integer noteId) {
        List<NoteReview> list = toList(LocalDateTime.of(date, LocalTime.now()), userId, noteId);
        repos.saveAll(list);
    }

    private static List<NoteReview> toList(LocalDateTime time, Integer userId, Integer noteId) {
        var obj = new Object() {
            LocalDateTime ldt = time;
        };
        LocalDateTime now = LocalDateTime.now();
        List<NoteReview> list = Stream.of(NoteReviewStrategyEnum.values())
                .map(e -> {
                    obj.ldt = obj.ldt.plus(e.intervalValue, e.intervalUnit);
                    Date date = DateUtils.toDate(obj.ldt);
                    NoteReviewStatusEnum status = obj.ldt.isBefore(now) ? REVIEWED : INITIAL;
                    Date reviewedDate = obj.ldt.isBefore(now) ? date : null;
                    return new NoteReview() //
                            .setUserId(userId)
                            .setNoteId(noteId)
                            .setReviewDate(date)
                            .setReviewedDate(reviewedDate)
                            .setStatus(status.code)
                            .setFrequency(e.frequency);
                })
                .collect(Collectors.toList());
        return list;
    }

    public void deleteByNoteId(Integer noteId) {
        repos.deleteByNoteId(noteId);
    }

}
